<script setup>
import { onMounted, ref } from 'vue'
import { getCategoryApi } from '@/api/category'
import { updateNovelApi } from '@/api/novel'
import { getNovelByIdApi } from '@/api/novel'
import { useRoute } from 'vue-router'
import router from '@/router'
// 获取头部id
const route = useRoute()
const novelId = ref()
novelId.value = parseInt(route.params.id.split('=')[1], 10)

//根据id查询作品
const getNovelById = async () => {
  const res = await getNovelByIdApi(novelId.value)
  // console.log(res)
  Ruleform.value.title = res.data.data.title
  Ruleform.value.categoryName = res.data.data.categoryName
  Ruleform.value.introduction = res.data.data.introduction
  console.log(Ruleform.value)
}
onMounted(() => {
  getNovelById()
})
// 表单绑定
const Ruleform = ref({
  title: '',
  introduction: '',
  categoryName: ''
})
const form = ref()
// 规则
const rule = ref({
  title: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '小说名字长度为2到20', trigger: 'blur' }
  ],
  introduction: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '小说介绍大于2个字符', trigger: 'blur' }
  ]
})
// 修改小说
const updateNovel = async () => {
  await form.value.validate()
  const res = await updateNovelApi(novelId.value, Ruleform.value)
  if (res.status === 200) {
    ElMessage.success('修改成功')
    router.push(`/novel/${novelId.value}`)
  }
}

// 获取分类
const categoryList = ref([])
const getCategory = async () => {
  const res = await getCategoryApi()
  // console.log(res.data.data)
  categoryList.value = res.data.data
}
getCategory()

const cancel = () => {
  router.push('/')
}
</script>
<template>
  <el-row :gutter="20">
    <el-col :span="12" :offset="6">
      <el-form
        :model="Ruleform"
        ref="form"
        :rules="rule"
        label-width="auto"
        style="max-width: 600px"
        class="el-form"
      >
        <el-form-item> 作品设置 </el-form-item>
        <el-form-item label="请输入书名" prop="title">
          <el-input v-model="Ruleform.title" />
        </el-form-item>
        <el-form-item label="请输入简介" prop="introduction">
          <el-input v-model="Ruleform.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="书籍分类">
          <el-select
            v-model="Ruleform.categoryName"
            placeholder="请选择你的书籍类型"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateNovel">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<style>
.el-form {
  margin-top: 100px;
}
</style>
